import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { login } from '../services/user';
import { reloadAuthorized } from '../utils/Authorized';
import { setToken, setUid, deleteToken } from '../utils/token';

export default {
  namespace: 'login',

  state: {},

  effects: {
    *login({ payload }, { call }) {
      const response = yield call(login, payload.params);
      if (response.isRight) {
        const { access_token: token, expire_at: expired, uid } = response.body;
        setToken(token, expired);
        setUid(uid);
        payload.onSuccess();
      }
    },
    *logout(_, { put }) {
      deleteToken();
      reloadAuthorized();
      yield put(
        routerRedux.push({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        })
      );
    },
  },

  reducers: {},
};
